<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Zend
 * @package    CategoryController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * @category   Zend
 * @package    CategoryController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Storefront_CatalogController extends Zend_Controller_Action
{

    /**
     * The logger
     * @var Zend_Log
     */
    protected $_logger;

    /**
     * Id of language
     * @var integer
     */
    protected $_languageId;

    /**
     * The data model for category
     * @var Storefront_Model_Category
     */
    protected $_categoryModel;

    /**
     * The AJAX flag
     * @var boolean
     */
    protected $_isAjax;

    /**
     * Initialize the controller
     */
    public function init()
    {
        // Get logger
        $this->_logger = Zend_Registry::get('log');

        // Get language from locale
        $locale = Zend_Registry::get('Zend_Locale');
        $languageModel = new Storefront_Model_Language();
        $this->_languageId = $languageModel->findIdByShortCode($locale->getLanguage());
        $this->view->language = $locale->getLanguage();

        $this->_categoryModel = new Storefront_Model_Category();
        $this->view->shopMode = Zend_Registry::get('config')->shopMode;

        // Check AJAX
        if ($this->getRequest()->isXmlHttpRequest()) {

            // If AJAX - turn of auto render
            $this->_helper->layout->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);
            $this->_isAjax = true;
        } else {

            // Get category tree
            $this->view->categoryTree = $this->_categoryModel->getTree($this->_languageId);

            // Get cart
            $cartModel = new Storefront_Model_Cart();
            $this->view->cartCount = $cartModel->count();

            // Get current url without language
            $this->view->currentUrl = str_replace('/' . $locale->getLanguage(), '', $this->_request->getRequestUri());

            // Form for search
            $form = new Storefront_Model_FormSearch();
            $form->setAction('/' . $locale->getLanguage() . '/search');
            $this->view->formSearch = $form;

            $this->view->shopName = Zend_Registry::get('config')->shopName;
            $this->view->shopTitle = Zend_Registry::get('config')->shopTitle;
            $this->view->shopCity = Zend_Registry::get('config')->shopCity;
        }
    }

    /**
     * Action for view
     */
    public function viewAction()
    {
        // Process category
        $categoryId = $this->_request->getParam('id');
        $category = $this->_categoryModel->findByIdAndLanguage($categoryId, $this->_languageId);
        if (!$category) {
            $this->_redirect();
        }
        $this->view->category = $category;

        // Get page from request
        $page = $this->_request->getParam('page');
        if (!$page) {
            $page = 1;
        }
        $this->view->page = $page;

        // Initialize form for content
        $form = new Storefront_Model_FormCatalog();
        $form->setAction('/' . $this->view->language . '/catalog/' . $categoryId);

        // Process row count
        $rowCount = $this->_request->getParam('rows');
        if (!$rowCount) {
            $rowCount = 10;
        }
        $this->view->rowCount = $rowCount;
        $form->rows->setValue($rowCount);

        // Process sort order
        $sort = $this->_request->getParam('sort');
        if (!$sort) {
            $sort = 'price';
        }
        $form->sort->setValue($sort);

        // Process sort direction
        $direction = $this->_request->getParam('direction');
        if (!$direction) {
            $direction = 'asc';
        }
        $form->direction->setValue($direction);

        // Add form to view
        $this->view->formCatalog = $form;

        // Get data for pagination
        $requestUrl = $this->_request->getRequestUri();
        $paginationUrl = substr($requestUrl, 0, strpos($requestUrl, "?"));
        $paginationUrl .= '?sort=' . $sort;
        $paginationUrl .= '&direction=' . $direction;
        $this->view->paginationUrl = $paginationUrl;

        // Get count of products
        $productModel = new Storefront_Model_Product();
        $productsCount = $productModel->getCountByCategoryAndLanguage($categoryId, $this->_languageId);
        $this->view->productsCount = $productsCount;
        $this->view->pageCount = ceil($productsCount / $rowCount);

        // Get products for page
        $this->view->products = $productModel->getByCategoryAndLanguage($categoryId, $this->_languageId, $sort, $direction, $page, $rowCount);

        if ($this->_isAjax) {

            // Render only AJAX contnet
            echo $this->view->render('/catalog/_products.phtml');
        } else {

            // Get categories for breadcrumb
            $this->view->breadcrumb = $this->_categoryModel->getParentCategories($categoryId, $this->_languageId);

            // Check products
            if (!$productsCount && $category->has_children) {

                // Get category children
                $this->view->children = $this->_categoryModel->getChildren($categoryId, $this->_languageId);
            }
        }

        // Get time of execution
        $startTime = Zend_Registry::get('startTime');
        $totalTime = round(microtime(true) - $startTime, 3);
        $this->_logger->debug(__METHOD__." spent $totalTime s");
    }

}

